<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="C++中的new/delete和malloc/free"><meta name="keywords" content="C++"><meta name="author" content="LiYang"><meta name="copyright" content="LiYang"><title>C++中的new/delete和malloc/free | 一条鲤鱼</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="一条鲤鱼" type="application/atom+xml">
</head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="Toggle article">Toggle site</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">Catalog</div><div class="sidebar-toc__progress"><span class="progress-notice">You've read</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#C-%E4%B8%ADnew-delete%E5%92%8Cmalloc-free%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-number">1.</span> <span class="toc-text">C++ 中new&#x2F;delete和malloc&#x2F;free的区别</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#C%E8%AF%AD%E8%A8%80%E4%B8%AD%E7%9A%84%E5%87%BD%E6%95%B0malloc%E5%92%8Cfree"><span class="toc-number">1.1.</span> <span class="toc-text">C语言中的函数malloc和free</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#C-%E4%B8%AD%E7%9A%84%E8%BF%90%E7%AE%97%E7%AC%A6new%E5%92%8Cdelete"><span class="toc-number">1.2.</span> <span class="toc-text">C++中的运算符new和delete</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#new-delete%E4%B8%8Emalloc-free%E4%B9%8B%E9%97%B4%E7%9A%84%E8%81%94%E7%B3%BB%E5%92%8C%E5%8C%BA%E5%88%AB"><span class="toc-number">1.3.</span> <span class="toc-text">new&#x2F;delete与malloc&#x2F;free之间的联系和区别</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%A1%A5%E5%85%85%EF%BC%9A-C-C-%E7%A8%8B%E5%BA%8F%E7%9A%84%E5%86%85%E5%AD%98%E5%88%86%E9%85%8D%E4%BB%8B%E7%BB%8D"><span class="toc-number">1.3.1.</span> <span class="toc-text">补充： C&#x2F;C++程序的内存分配介绍</span></a></li></ol></li></ol></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">LiYang</div><div class="author-info__description text-center"></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">Articles</span><span class="pull-right">13</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">Tags</span><span class="pull-right">6</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">Categories</span><span class="pull-right">7</span></a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">一条鲤鱼</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"></span></div><div id="post-info"><div id="post-title">C++中的new/delete和malloc/free</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2021-12-07</time><span class="post-meta__separator">|</span><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">编程语言</a><i class="fa fa-angle-right" aria-hidden="true"></i><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/C/">C++</a></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><hr>
<h1 id="C-中new-delete和malloc-free的区别"><a href="#C-中new-delete和malloc-free的区别" class="headerlink" title="C++ 中new/delete和malloc/free的区别"></a>C++ 中new/delete和malloc/free的区别</h1><p>参考链接:<a target="_blank" rel="noopener" href="https://www.cnblogs.com/iloverain/p/5633281.html">https://www.cnblogs.com/iloverain/p/5633281.html</a></p>
<hr>
<h2 id="C语言中的函数malloc和free"><a href="#C语言中的函数malloc和free" class="headerlink" title="C语言中的函数malloc和free"></a>C语言中的函数malloc和free</h2><p>(1) 函数malloc和free在**头文件&lt;stdlib.h&gt;**中的原型及参数</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span> * <span class="title">malloc</span><span class="params">(<span class="keyword">size_t</span> size)</span></span></span><br></pre></td></tr></table></figure>

<p><strong>动态配置内存，大小由size决定，返回值成功时为任意类型指针，失败时为NULL。</strong> </p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span>  <span class="title">free</span><span class="params">(<span class="keyword">void</span> *ptr)</span></span></span><br></pre></td></tr></table></figure>

<p><strong>释放动态申请的内存空间，调用free( )后ptr所指向的内存空间被收回，如果ptr指向未知地方或者指向的空间已被收回，则会发生不可预知的错误，如果ptr为NULL，free不会有任何作用。</strong></p>
<hr>
<p>(2) C语言中典型用法</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">T *p = ( T* )<span class="built_in">malloc</span>( <span class="keyword">sizeof</span>(T) * n)  <span class="comment">//T为任意数据类型</span></span><br><span class="line"><span class="keyword">if</span>(<span class="literal">NULL</span>==p)&#123;</span><br><span class="line">	<span class="built_in">printf</span>(“<span class="built_in">malloc</span> fail!\n”);</span><br><span class="line">	……<span class="comment">//相关资源收回的处理</span></span><br><span class="line">	<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">&#125;</span><br><span class="line">… …<span class="comment">//此过程不能改变指针p的指向</span></span><br><span class="line"><span class="built_in">free</span>(p);</span><br></pre></td></tr></table></figure>

<p>注意：malloc后通常要对返回值进行判断，避免发生不必要的错误。</p>
<hr>
<p>(3) 内存说明</p>
<p>malloc函数动态申请的内存空间是<strong>在堆里</strong>(而一般局部变量存于栈里)，并且<strong>该段内存不会被初始化</strong>，与全局变量不一样，如果不采用手动free()加以释放，则该段内存一直存在，直到程序退出才被系统，所以为了合理使用内存，在不适用该段内存时，应该调用free()。另外，<strong>如果在一个函数里面使用过malloc，最好要配对使用free，否则容易造成内存泄露。</strong></p>
<hr>
<h2 id="C-中的运算符new和delete"><a href="#C-中的运算符new和delete" class="headerlink" title="C++中的运算符new和delete"></a>C++中的运算符new和delete</h2><p><strong>new和delete是C++中的运算符</strong>，不是库函数，不需要库的支持，同时，他们是封装好的重载运算符，并且可以再次进行重载。</p>
<p>C++中使用new的例子：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//new运算的例子</span></span><br><span class="line"><span class="keyword">new</span> <span class="keyword">int</span>  <span class="comment">//开辟一个存放整数的存储空间，返回一个指向该存储空间的地址</span></span><br><span class="line"><span class="keyword">new</span> <span class="built_in"><span class="keyword">int</span></span>(<span class="number">100</span>)  <span class="comment">//同上，并指定该整数的初值为100</span></span><br><span class="line"><span class="keyword">new</span> <span class="keyword">char</span>[<span class="number">100</span>] <span class="comment">//开辟一个存放字符数组（100个元素）的空间，返回首地址</span></span><br><span class="line"><span class="keyword">new</span> <span class="keyword">int</span>[<span class="number">4</span>][<span class="number">5</span>]<span class="comment">//开辟一个存放二维数组的空间，返回首元素的地址</span></span><br><span class="line"><span class="keyword">float</span> *p=<span class="keyword">new</span> <span class="built_in"><span class="keyword">float</span></span>(<span class="number">3.14157</span>) <span class="comment">//开辟一个存放单精度的空间，并指定该数的初值为3.14157，</span></span><br><span class="line">                              将返回的该空间的地址赋给指针变量p</span><br></pre></td></tr></table></figure>

<p><strong>注意：用new分配数组空间不能指定初值，若无法正常分配，则new会返回一个空指针NULL,用户可以根据此判断是否分配成功。</strong></p>
<p>delete运算符使用的一般格式：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">delete  指针变量  </span><br><span class="line">delete  [ ] 指针变量（对数组）</span><br></pre></td></tr></table></figure>

<p>（1）     <strong>new是动态分配内存的运算符，自动计算需要分配的空间</strong>，在C++中，它属于重载运算符，可以对多种数据类型形式进行分配内存空间，比如int型、char型、结构体型和类等的动态申请的内存分配，分配类的内存空间时，同时调用类的构造函数，<strong>对内存空间进行初始化，即完成类的初始化工作。</strong></p>
<p>（2）     <strong>delete是撤销动态申请的内存运算符。</strong>delete与new通常配对使用，与new的功能相反，可以对多种数据类型形式的内存进行撤销，包括类，撤销类的内存空间时，<strong>它要调用其析构函数，完成相应的清理工作，收回相应的内存资源。</strong></p>
<p>（3）     典型用法</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//类的类型 *p = new 类的类型； delete p；如：</span></span><br><span class="line"><span class="keyword">int</span> *p = <span class="keyword">new</span> <span class="keyword">int</span>;                   </span><br><span class="line"><span class="keyword">delete</span> p;</span><br><span class="line"><span class="keyword">char</span> *p = <span class="keyword">new</span> <span class="keyword">char</span>;</span><br><span class="line"><span class="keyword">delete</span> p;</span><br><span class="line"><span class="comment">//注意，指针p存于栈中，p所指向的内存空间却是在堆中。</span></span><br><span class="line">Obj * p = <span class="keyword">new</span> Obj[<span class="number">100</span>];           </span><br><span class="line"><span class="keyword">delete</span> []p;</span><br><span class="line"><span class="comment">//注意，new申请数组，delete删除的形式需要加括号“[ ]”，表示对数组空间的操作，总之，申请形式如何，释放的形式就如何。</span></span><br></pre></td></tr></table></figure>

<p>（4）     内存说明。<strong>new申请的内存也是存于堆中，所以在不需要使用时，需要delete手动收回。</strong></p>
<hr>
<h2 id="new-delete与malloc-free之间的联系和区别"><a href="#new-delete与malloc-free之间的联系和区别" class="headerlink" title="new/delete与malloc/free之间的联系和区别"></a>new/delete与malloc/free之间的联系和区别</h2><ul>
<li><p>(1)     <strong>malloc/free和new/delete的联系</strong></p>
<ul>
<li>a）     存储方式相同。malloc和new动态申请的内存都位于堆中。申请的内存都不能自动被操作系统收回，都需要配套的free和delete来释放。</li>
<li>b）     除了带有构造函数和析构函数的类等数据类型以外，对于一般数据类型，如int、char等等，两组动态申请的方式可以通用，作用效果一样，只是形式不一样。</li>
<li>c）     内存泄漏对于malloc或者new都可以检查出来的，区别在于new可以指明是那个文件的那一行，而malloc没有这些信息。</li>
<li>d）     两组都需要配对使用，malloc配free，new配delete，注意，这不仅仅是习惯问题，如果不配对使用，容易造成内存泄露。同时，在C++中，两组之间不能混着用，虽说有时能编译过，但容易存在较大的隐患。</li>
</ul>
</li>
<li><p><strong>(2)     malloc/free和new/delete的区别</strong></p>
<ul>
<li><p>a）     malloc和free返回void类型指针，new和delete直接带具体类型的指针。</p>
</li>
<li><p>b）     malloc和free属于C语言中的函数，需要库的支持，而new/delete是C++中的运算符，况且可以重载，所以new/delete的执行效率高些。C++中为了兼用C语法，所以保留malloc和free的使用，但建议尽量使用new和delete。</p>
</li>
<li><p>c）     在C++中， new是类型安全的，而malloc不是。例如：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span>* p = <span class="keyword">new</span> <span class="keyword">char</span>[<span class="number">10</span>];          <span class="comment">// 编译时指出错误</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">delete</span> []p;                   <span class="comment">//对数组需要加中括号“[ ]”</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span>* p = <span class="built_in">malloc</span>(<span class="keyword">sizeof</span>(<span class="keyword">char</span> )*<span class="number">10</span>);  <span class="comment">// 编译时无法指出错误</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">free</span> (p);                    <span class="comment">//只需要所释放内存的头指针</span></span><br></pre></td></tr></table></figure></li>
<li><p>d）     使用new动态申请类对象的内存空间时，类对象的构建要调用构造函数，相当于对内存空间进行了初始化。而malloc动态申请的类对象的内存空间时，不会初始化，也就是说申请的内存空间无法使用，因为类的初始化是由构造函数完成的。delete和free的意义分别于new和malloc相反。</p>
</li>
<li><p>e）     不能用malloc和free来完成类对象的动态创建和删除。</p>
</li>
</ul>
</li>
</ul>
<hr>
<h3 id="补充：-C-C-程序的内存分配介绍"><a href="#补充：-C-C-程序的内存分配介绍" class="headerlink" title="补充： C/C++程序的内存分配介绍"></a>补充： C/C++程序的内存分配介绍</h3><p>（1）栈内存分配运算内置于处理器的指令集中，一般使用寄存器来存取，效率很高，但是分配的内存容量有限。 一般局部变量和函数参数的暂时存放位置。</p>
<p>（2） 堆内存，亦称动态内存。如malloc和new申请的内存空间。动态内存的生存期由程序员自己决定，使用非常灵活。 </p>
<p>（3）全局代码区：从静态存储区域分配。内存在程序编译的时候就已经分配好，这块内存在程序的整个运行期间都存在。例如全局变量，static变量。 </p>
<p>（4）常量区：文字常量分配在文字常量区，程序结束后由系统释放。 </p>
<p>（5）代码区：存放整个程序的代码，因为存储是数据和代码分开存储的。</p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">LiYang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://example.com/2021/12/07/C-中的new-delete和malloc-free/">http://example.com/2021/12/07/C-中的new-delete和malloc-free/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/C/">C++</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2022/04/18/C-%E4%B8%AD%E7%9A%84operator-new%E5%92%8Cplacement-new/"><i class="fa fa-chevron-left">  </i><span>C++中的operator_new和placement_new</span></a></div><div class="next-post pull-right"><a href="/2021/12/02/%E4%BD%8D%E5%9B%BE%E6%8E%92%E5%BA%8F/"><span>位图排序</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2013 - 2022 By LiYang</div><div class="framework-info"><span>Driven - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>Theme - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script></body></html>